package com.iflytek.uc.controller;

import java.util.Enumeration;
import java.util.List;

import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.iflytek.uc.domain.Account;
import com.iflytek.uc.domain.EntityType;
import com.iflytek.uc.domain.EntityType.EntityCategory;
import com.iflytek.uc.exceptions.AccoutDisabledException;
import com.iflytek.uc.exceptions.NoSuchAccountException;
import com.iflytek.uc.exceptions.PasswordErrorException;
import com.iflytek.uc.service.AccountService;
import com.iflytek.uc.service.ConfigService;
import com.iflytek.uc.service.EntityTypeService;
import com.iflytek.uc.util.AuthenticationFilter;
import com.iflytek.uc.vo.Menu;

@Controller
public class HomeController {
	private static final Logger LOG = Logger.getLogger(HomeController.class);
	
	private static final Menu[] MENUS = new Menu[] {
		new Menu("", "系统", "", new Menu[] {
				new Menu("", "信息", "system/infomation"),
				new Menu("", "数据库设置", "system/database"),
				new Menu("", "服务设置", "system/service"),
				new Menu("", "参与方设置", "system/entity?entityCategory=PARTY"),
				new Menu("", "资源设置", "system/entity?entityCategory=RESOURCE"),
				new Menu("", "权限设置", "system/authorization"),
				new Menu("", "导出", "system/export"),
				new Menu("", "导入", "system/import")
		}),
		new Menu("ENTITY", "参与方", "PARTY", new Menu[] {
				//new Menu("", "参与方", "about:blank")
		}),
		new Menu("", "账号", "", new Menu[] {
				new Menu("", "账号管理", "account/manage")
		}),
		new Menu("ENTITY", "资源", "RESOURCE", new Menu[] {
				//new Menu("", "资源", "about:blank")
		}),
		new Menu("", "授权", "", new Menu[] {
				new Menu("", "授权查询", "authorization/query")
		})
	};
	
	@Autowired
	private AccountService accountService;
	
	@Autowired
	private ConfigService configService;
	
	@Autowired
	private EntityTypeService entityTypeService;
	
	@RequestMapping("/admin/index")
	public ModelAndView index() {
		LOG.info("<open index page>");
		
		Account acct = AuthenticationFilter.getLoginAccount();
		LOG.debug("login account: " + acct);
		
		ModelAndView mv = new ModelAndView("index");
		
		Menu[] subMenus = getSubMenus(0);
		mv.addObject("topMenus", MENUS);
		mv.addObject("subMenus", subMenus);
		
		mv.addObject("applicationTitle", configService.getApplicationTitle());
		mv.addObject("loginAccount", acct);
		
		return mv;
	}
	
	@RequestMapping("/login")
	public ModelAndView login(HttpSession session, String accountName, String password) {
		if (StringUtils.isBlank(accountName) && StringUtils.isBlank(password)) {
			ModelAndView mv = new ModelAndView("login");
			mv.addObject("applicationTitle", configService.getApplicationTitle());
			return mv;
		}
		else {
			return doLogin(session, accountName, password);
		}
	}
	
	@RequestMapping("/logout")
	public String logout(HttpSession session) {
		@SuppressWarnings("unchecked")
		Enumeration<String> names = session.getAttributeNames();
		while (names.hasMoreElements()) {
			String name = names.nextElement();
			session.removeAttribute(name);
		}
		return "redirect:/login";
	}
	
	@RequestMapping("/admin/index/menus")
	@ResponseBody
	public Menu[] getIndexPageMenus(String id) {
		int index = 0;
		if (StringUtils.contains(id, "_")) {
			String s = StringUtils.substring(id, StringUtils.indexOf(id, "_") + 1);
			index = Integer.parseInt(s);
		}
		else {
			index = Integer.parseInt(id);
		}
		
		Menu[] subs = getSubMenus(index);
		return subs;
	}

	private ModelAndView doLogin(HttpSession session, String accountName, String password) {
		String error = StringUtils.EMPTY;
		
		try {
			Account account = accountService.doLogin(accountName, password);
			session.setAttribute(AuthenticationFilter.LOGIN_ACCOUNT_SESSION_KEY, account);
			LOG.info("user login: " + account.getName());
			
			ModelAndView mv = new ModelAndView("redirect:admin/index");
			return mv;
		}
		catch (NoSuchAccountException e) {
			error = "登录账号不存在";
		}
		catch (AccoutDisabledException e) {
			error = "登录账号已被停用，请与管理员联系";
		}
		catch (PasswordErrorException e) {
			error = "登录账号或密码错误";
		}
		catch (Exception e) {
			LOG.error("", e);
			error = "登录时发生未知错误，请与管理员联系";
		}
		
		return loginError(error);
	}
	
	private ModelAndView loginError(String message) {
		ModelAndView mv = new ModelAndView("login");
		mv.addObject("applicationTitle", configService.getApplicationTitle());
		mv.addObject("message", message);
		return mv;
	}

	private Menu[] getSubMenus(int index) {
		if (index < 0 || index >= MENUS.length) {
			return new Menu[0];
		}
		
		Menu menu = MENUS[index];
		if (StringUtils.equals("ENTITY", menu.getId())) {
			EntityCategory category = EntityCategory.valueOf(menu.getUrl());
			List<EntityType> types = entityTypeService.getRootEntityTypes(category);
			
			Menu[] r = new Menu[types.size()];
			for (int i = 0; i < types.size(); i ++) {
				r[i] = new Menu("", types.get(i).getDisplayName(), 
						"entity/manage?entityType=" + types.get(i).getName());
			}
			return r;
		}
		else {
			return menu.getChildren();
		}
	}
}
